﻿using Calendar;
using Iacym.Entities;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Iacym.BusinessLogic;
using Microsoft.Practices.Unity;

namespace Iacym.UI
{
    public partial class FrmCitas : Form//, IForm
    {
        [Dependency]
        public IAgendumBL agendaBL { get; set; }

        [Dependency]
        public IPersonaBL personaBL { get; set; }

        Agendum _currentAgenda { get; set; }

        List<Appointment> m_Appointments;

        [Dependency]
        public IUsuarioMenuBL usuMenuBL { get; set; }

        public FrmCitas()
        {
            InitializeComponent();
            this.BuildUp();
            this.Location = Screen.PrimaryScreen.WorkingArea.Location;
            this.Size = Screen.PrimaryScreen.WorkingArea.Size;
            verDias.StartDate = DateTime.Now;
            verDias.NewAppointment += new NewAppointmentEventHandler(dayCalendar_NewAppointment);
            verDias.ResolveAppointments += new Calendar.ResolveAppointmentsEventHandler(this.dayCalendar_ResolveAppointments);
        }

        public USUARIO currentUsuarioCita { get; set; }

        private void BtnNuevo_Click(object sender, EventArgs e)
        {
            FrmMttoCitas mttoCita = new FrmMttoCitas();
            mttoCita.Nuevo();
            mttoCita.ShowDialog();
            CargarDatos();
        }

        void dayCalendar_NewAppointment(object sender, NewAppointmentEventArgs args)
        {
            Appointment m_Appointment = new Appointment();

            m_Appointment.StartDate = args.StartDate;
            m_Appointment.EndDate = args.EndDate;
            m_Appointment.Title = args.Title;
            m_Appointment.Group = "2";

            m_Appointments.Add(m_Appointment);
        }

        private void dayCalendar_ResolveAppointments(object sender, ResolveAppointmentsEventArgs args)
        {
            List<Appointment> m_Apps = new List<Appointment>();

            foreach (Appointment m_App in m_Appointments)
            {
                if ((m_App.StartDate >= args.StartDate) && (m_App.StartDate <= args.EndDate))
                {
                    m_Apps.Add(m_App);
                }
            }

            args.Appointments = m_Apps;
        }

        private void monthCalendar1_DateChanged(object sender, DateRangeEventArgs e)
        {
            verDias.StartDate = calendarioMensual.SelectionStart;
        }

        private void CargarDatos()
        {
            //var citas = agendaBL.GetAllFromAgenda();
            List<Agendum> citas = new List<Agendum>(agendaBL.GetAllFromAgenda());
            m_Appointments = new List<Appointment>();

            foreach (var item in citas)
            {
                Appointment m_App = new Appointment();
                m_App.StartDate = item.FechaInicio;
                m_App.EndDate = item.FechaFin;
                if (item.PERSONA == null)
                {
                    var persona = personaBL.GetFromPersonaById(item.PersonaId);
                    m_App.Title = persona.NombreCompleto + "\n" + item.Motivo;
                }
                else
                    m_App.Title = item.PERSONA.NombreCompleto + "\n" + item.Motivo;
                m_App.Color = Color.Red;
                m_App.Locked = true;

                m_Appointments.Add(m_App);

                verDias.Invalidate();
            }
        }

        public void menuLlena()
        {
            var datoUsuario = usuMenuBL.GetAllFromUsuarioByPersonaFromLogin(currentUsuarioCita.PERSONA.Dni);

            var permisos = (from p in usuMenuBL.GetAllUsuarioMenu(datoUsuario.UsuarioId)
                            select p.MENU.Tag.ToString()).ToArray();

            System.Windows.Forms.Button[] botones = new System.Windows.Forms.Button[] { 
            this.BtnEditar,this.BtnNuevo};

            var noVisible = from nv in botones
                            where !permisos.Contains(nv.Tag.ToString())
                            select nv;

            noVisible.ToList().ForEach(nv => nv.Enabled = false);
        }

        private void FrmCitas_Load(object sender, EventArgs e)
        {
            if (currentUsuarioCita != null)
            {
                menuLlena();
                CargarDatos();
            }
            else
            {
                CargarDatos();
            }
        }

        private void verDias_Click(object sender, EventArgs e)
        {
            //Intentamos obtener HoraInicio y HoraFin el cual usaré en un método directo a BD
            var _app = verDias.SelectedAppointment;

            if (_app != null)
            {
                var _agenda = agendaBL.BuscarAgendaPorFechas(_app.StartDate, _app.EndDate);

                if (_agenda != null)
                {
                    _currentAgenda = _agenda;
                }
            }
        }

        private void verDias_DoubleClick(object sender, EventArgs e)
        {
            //Rol de pastor = 1
            if (currentUsuarioCita.PERSONA.USUARIO.RolId == 1)
            {
                if (_currentAgenda != null)
                {
                    FrmMttoDetalleCitas frm = new FrmMttoDetalleCitas();
                    frm._currentAgenda = _currentAgenda;
                    frm.Editar();
                    frm.ShowDialog();
                }
            }
            else
            {
                MessageBox.Show("No tiene permiso para ver el detalle de la cita.", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void BtnEditar_Click(object sender, EventArgs e)
        {
            if (_currentAgenda != null)
            {
                if (_currentAgenda.FechaInicio.Date < DateTime.Now.Date)
                {
                    MessageBox.Show("Esta cita ya expiró, no se puede editar.", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    if (_currentAgenda.PERSONA == null)
                    {
                        var persona = personaBL.GetFromPersonaById(_currentAgenda.PersonaId);
                        _currentAgenda.PERSONA = persona;
                    }
                    FrmMttoCitas frm = new FrmMttoCitas();
                    frm._currentAgenda = _currentAgenda;
                    frm.Editar();
                    frm.ShowDialog();
                    CargarDatos();
                }
            }
            else
            {
                MessageBox.Show("Seleccione un ítem válido por favor.", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
    }
}
